package com.dc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.DateUtil;
import com.dc.common.ResponseResultVO;
import com.dc.entity.SparePart;
import com.dc.entity.SparePartDetail;
import com.dc.entity.SparePartRelation;
import com.dc.entity.WorkOrder;
import com.dc.entity.ro.SparePartRelationRO;
import com.dc.exceptions.BizException;
import com.dc.mapper.SparePartDetailMapper;
import com.dc.mapper.SparePartMapper;
import com.dc.mapper.SparePartRelationMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.service.SparePartRelationService;
import com.dc.util.RedisUtil;
import com.dc.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class SparePartRelationServiceImpl extends ServiceImpl<SparePartRelationMapper, SparePartRelation> implements SparePartRelationService {

    @Resource
    private SparePartRelationMapper sparePartRelationMapper;
    @Resource
    private SparePartMapper sparePartMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SparePartDetailMapper sparePartDetailMapper;
    @Resource
    private WorkOrderMapper workOrderMapper;

    @Override
    @Transactional
    public ResponseResultVO insertSparePartRelation(SparePartRelationRO ro) {
        List<SparePart> info = ro.getInfo();
        //出入库主记录入库
        SparePartRelation sparePartRelation = new SparePartRelation();
        BeanUtils.copyProperties(ro, sparePartRelation);
        sparePartRelation.setId(SnowflakeIdWorker.generateId());
        sparePartRelation.setInOutTime(DateUtil.parseStrToDate(ro.getInOutTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        sparePartRelation.setStockNum(info.stream().mapToInt(SparePart::getStockNum).sum());
        sparePartRelation.setNumber(0 == ro.getType() ? redisUtil.serialNumber("WXPRK") : redisUtil.serialNumber("WXPCK"));
        sparePartRelationMapper.insert(sparePartRelation);
        int insert = 0;
        //修改库存
        for (SparePart sparePart : info) {
            SparePart data = sparePartMapper.selectById(sparePart.getId());
            if (null != data) {
                int num = 0;
                if (0 == ro.getType()) {
                    //入库
                    num = sparePart.getStockNum() + data.getStockNum();
                } else {
                    //出库
                    num = data.getStockNum() - sparePart.getStockNum();
                    if (num < 0) {
                        throw new BizException("出库数量异常!");
                    }
                }
                data.setStockNum(num);
                sparePartMapper.updateById(data);
            }
            SparePartDetail sparePartDetail = new SparePartDetail();
            BeanUtils.copyProperties(sparePart, sparePartDetail);
            sparePartDetail.setId(SnowflakeIdWorker.generateId());
            sparePartDetail.setPartId(sparePart.getId());
            sparePartDetail.setRelationId(sparePartRelation.getId());
            insert = sparePartDetailMapper.insert(sparePartDetail);

        }
        return ResponseResultVO.insertResult(insert);
    }

    @Override
    public ResponseResultVO updateSparePartRelation(SparePartRelationRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        SparePartRelation sparePartRelation = new SparePartRelation();
        BeanUtils.copyProperties(ro, sparePartRelation);
        return ResponseResultVO.updateResult(sparePartRelationMapper.updateById(sparePartRelation));
    }

    @Override
    public ResponseResultVO deleteSparePartRelation(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        return ResponseResultVO.deleteResult(sparePartRelationMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectSparePartRelationList(SparePartRelationRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        LambdaQueryWrapper<SparePartRelation> queryWrapper = new QueryWrapper<SparePartRelation>().lambda();
        queryWrapper.eq(null != ro.getType(), SparePartRelation::getType, ro.getType());
        if (StringUtils.isNotBlank(ro.getGoodsName())) {
            List<SparePartDetail> sparePartDetails = sparePartDetailMapper.selectList(new QueryWrapper<SparePartDetail>().lambda().like(SparePartDetail::getGoodsName, ro.getGoodsName()));
            if (CollectionUtils.isNotEmpty(sparePartDetails)) {
                Set<Long> relationIds = sparePartDetails.stream().map(SparePartDetail::getRelationId).collect(Collectors.toSet());
                queryWrapper.in(SparePartRelation::getId, relationIds);
            } else {
                return ResponseResultVO.resultList(new Page(), ro);
            }
        }
        if (StringUtils.isNotBlank(ro.getSerialNumber())) {
            List<SparePartDetail> sparePartDetails = sparePartDetailMapper.selectList(new QueryWrapper<SparePartDetail>().lambda().like(SparePartDetail::getSerialNumber, ro.getSerialNumber()));
            if (CollectionUtils.isNotEmpty(sparePartDetails)) {
                Set<Long> relationIds = sparePartDetails.stream().map(SparePartDetail::getRelationId).collect(Collectors.toSet());
                queryWrapper.in(SparePartRelation::getId, relationIds);
            } else {
                return ResponseResultVO.resultList(new Page(), ro);
            }
        }
        queryWrapper.eq(StringUtils.isNotBlank(ro.getBillNo()), SparePartRelation::getBillNo, ro.getBillNo());
        queryWrapper.eq(null != ro.getReceivingPurpose(), SparePartRelation::getReceivingPurpose, ro.getReceivingPurpose());
        queryWrapper.orderByDesc(SparePartRelation::getCreateTime);
        IPage<SparePartRelation> iPage = sparePartRelationMapper.selectPage(page, queryWrapper);
        iPage.getRecords().forEach(s -> {
            List<SparePartDetail> sparePartDetails = sparePartDetailMapper.selectList(new QueryWrapper<SparePartDetail>().lambda().eq(SparePartDetail::getRelationId, s.getId()));
            s.setSparePartDetails(sparePartDetails);
        });
        return ResponseResultVO.resultList(iPage, ro);

    }

    @Override
    public ResponseResultVO selectBillList(String type) {
        ResponseResultVO.checkParameterIsNotNull(type, "参数不能为空");
        List<WorkOrder> workOrders = workOrderMapper.selectList(new QueryWrapper<WorkOrder>().lambda().eq(WorkOrder::getType, "0".equals(type) ? 2 : 1).ne(WorkOrder::getStatus, 2));
        return ResponseResultVO.successResult(workOrders);
    }
}
